import { useLocation } from 'react-router';
import { useProject } from '@src/utils/project';
import { useUrlQueryParam } from '@src/utils/url';
import { useCallback, useMemo } from 'react';
import { useTask } from '@src/utils/task';

/**
 * 获取浏览器地址 当前 project的id
 */
export const useProjectIdInUrl = () => {
  const { pathname } = useLocation();
  const id = pathname.match(/projects\/(\d+)/)?.[1];
  return Number(id);
};

/**
 * ==================================    根据当前的projectId 获取 project的对象   ========================================
 * @constructor
 */
export const useProjectInUrl = () => useProject(useProjectIdInUrl());

/**
 * ==================================    获取看板查询参数    ========================================
 * @constructor
 */
export const useKanbanSearchParams = () => ({ projectId: useProjectIdInUrl() });
/**
 * ==================================    看板 查询key   ========================================
 * @constructor
 */
export const useKanbansQueryKey = () => ['kanbans', useKanbanSearchParams()];
export const useTasksSearchParams = () => {
  // 获取浏览器中的这几项参数的查询对象
  const [param] = useUrlQueryParam(['name', 'typeId', 'processorId', 'tagId']);
  // 获取 projectId
  const projectId = useProjectIdInUrl();
  //
  return useMemo(
    () => ({
      projectId,
      typeId: Number(param.typeId) || undefined,
      processorId: Number(param.processorId) || undefined,
      tagId: Number(param.tagId) || undefined,
      name: param.name,
    }),
    [projectId, param]
  );
};

/**
 * ==================================    任务 查询key   ========================================
 * @constructor
 */
export const useTasksQueryKey = () => ['tasks', useTasksSearchParams()];

/**
 * ==================================    任务 弹窗 ========================================
 * @constructor
 */
export const useTasksModal = () => {
  const [{ editingTaskId }, setEditingTaskId] = useUrlQueryParam(['editingTaskId']);
  const { data: editingTask, isLoading } = useTask(Number(editingTaskId));
  const startEdit = useCallback(
    (id: number) => {
      setEditingTaskId({ editingTaskId: id });
    },
    [setEditingTaskId]
  );
  const close = useCallback(() => {
    setEditingTaskId({ editingTaskId: '' });
  }, [setEditingTaskId]);
  return {
    editingTaskId,
    editingTask,
    startEdit,
    close,
    isLoading,
  };
};
